package com.situ.mall.product.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.situ.mall.common.util.Result;
import com.situ.mall.pojo.entity.product.Collect;
import com.situ.mall.pojo.entity.product.Product;
import com.situ.mall.product.service.ICollectService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Sun Huijuan
 * @since 2024-10-17
 */
@RestController
@RequestMapping("/product/collect")
public class CollectController {
	@Autowired
	private ICollectService collectService;
	
	@GetMapping("/getCollect/{id}")
	public Result<List<Product>> getCollect(@PathVariable Long id){
		List<Product> list=collectService.getCollect(id);
		return Result.ok(list);
	}
	
	@PostMapping("/add")
	public Result add(@RequestBody Collect collect){
		List<Collect> list=collectService.selectAllList(collect.getProductId(),collect.getUserId());
		if(!ObjectUtils.isEmpty(list)){
			for(Collect collect1:list){
				if(collect1.getProductId().equals(collect.getProductId())){
					collectService.updateCollect(collect.getUserId(),collect.getProductId());
				}
			}
		}else {
			collectService.save(collect);
		}
		return Result.ok("添加收藏成功！");
	}
	
	@DeleteMapping("/deleteCollect/{id}")
	public Result deleteCollect(@PathVariable Long id){
		collectService.removeById(id);
		return Result.ok("取消收藏成功！");
	}
	
	@DeleteMapping("/removeCollect/{id}/{productId}")
	public Result removeCollect(@PathVariable Long id, @PathVariable Long productId){
		UpdateWrapper<Collect> wrapper=new UpdateWrapper<>();
		wrapper.set("deleted",1).eq("user_id",id).eq("product_id",productId);
		collectService.update(wrapper);
		return Result.ok("取消收藏成功！");
	}
	
	@GetMapping("/selectUserCollect/{id}")
	public Result<List<Collect>> selectUserCollect(@PathVariable Long id){
		QueryWrapper<Collect> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq(!ObjectUtils.isEmpty(id),"user_id",id);
		List<Collect> list=collectService.list(queryWrapper);
		return Result.ok(list);
	}
	
}

